package com.atguigu.gulimall.ware.config;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
public class MyRabbitConfig {

    /**
     * 将rabbitMQ的消息转换为json
     *
     */
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

//    @RabbitListener(queues = "stock.release.stock.queue")
//    public void handle(Message message){}

    @Bean
    public Exchange stockEventExchange(){
        return new TopicExchange(
                "stock-event-exchange",
                true,
                false);
    }

    //创建消息接收队列
    //exclusive,是否排他，只能有一个人连接队列
    //false,很多人都可以连接队列，谁抢到算谁的
    @Bean
    public Queue stockReleaseStockQueue(){
        return new Queue(
                "stock.release.stock.queue",
                true,false,false);
    }

    //创建死信队列，里面的消息是死信，一定时间后死亡被丢到其他的交换机的队列中去
    @Bean
    public Queue stockDelayQueue(){

        HashMap<String, Object> arguments = new HashMap<>();

        //信死了交给哪个交换机
        arguments.put("x-dead-letter-exchange","stock-event-exchange");
        //信死了交给交换机传给哪个路由
        arguments.put("x-dead-letter-routing-key","stock.release");
        //死信的存活时间
        arguments.put("x-message-ttl",120000);

        return new Queue("stock.delay.queue",
                true,false,false,arguments);
    }


    //创建绑定关系，即交换发送消息给队列的的规则，死信路由
    @Bean
    public Binding stockReleaseBinding(){

        //stock.release.#以 stock.release 开头的消息都 都发给
        return new Binding("stock.release.stock.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.release.#",
                null);

    }

    @Bean
    //接收死信消息路由,即要锁库存的商品s
    public Binding stockLockedBinding(){

        //stock.release.#以 stock.release 开头的消息都 都发给
        return new Binding("stock.delay.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.locked",
                null);

    }

}
